import { useEffect, useState } from "react";

const isVoid = (value: unknown) => value === undefined || null || "";

export const cleanObject = <
  T extends { [key: string]: unknown },
  K extends keyof T
>(
  obj: T
): object => {
  const result = { ...obj };

  Object.keys(result).forEach((key) => {
    if (isVoid(result[key as K])) {
      delete result[key as K];
    }
  });

  return result;
};

export const useMount = (callback: () => void) => {
  useEffect(() => {
    callback();
    // eslint-disable-next-line
  }, []);
};

export const useDebounce = <V>(value: V, wait?: number): V => {
  let [deBounceValue, setDebounceValue] = useState(value);

  useEffect(() => {
    let timeout = setTimeout(() => setDebounceValue(value), wait);
    return () => clearTimeout(timeout);
  }, [value, wait]);

  return deBounceValue;
};

export const useArray = <T>(array: Array<T>) => {
  let [value, setValue] = useState(array);
  const add = (item: T) => setValue([...value, item]);
  const clear = () => setValue([]);

  const removeByIndex = (index: number) => {
    const copy = value.slice();

    if (index >= 0 && index < copy.length) {
      copy.splice(index, 1);
      setValue(copy);
    } else {
      throw new Error("index is not in the array range");
    }
  };

  return {
    value,
    setValue,
    add,
    clear,
    removeByIndex,
  };
};
